<script setup lang="ts">
import { onMounted, ref } from "vue";
import { KnoDoc } from "@/views/domain/knowledge/api/knoDoc";
import {
  genFileId,
  UploadProps,
  UploadRawFile,
  UploadUserFile
} from "element-plus";
import { getToken } from "@/utils/auth";

const emit = defineEmits(["submit"]);

const props = defineProps<{
  namespace: string;
  modelValue?: KnoDoc;
}>();

const show = ref(false);
const model = ref<KnoDoc>();
const initModel = () => {
  model.value = props.modelValue || {
    namespace: props.namespace,
    embedModel: "nomic-embed-text:latest"
  };
};

const token = getToken();

const selectFiles = ref<UploadUserFile[]>();
const upload = ref();
const handleClose = () => {
  show.value = false;
};

const handleSubmit = () => {
  handleClose();
  // if (!model.value.sourcePath) {
  //   model.value.sourcePath = selectFiles.value?.[0].raw?.webkitRelativePath;
  // }
  upload.value.submit();
};

const onFileUploaded = () => {
  emit("submit", model.value);
};

const handleExceed: UploadProps["onExceed"] = files => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
};

const onFileChange = file => {
  if (!model.value.title) {
    model.value.title = file.name;
  }
};

onMounted(() => {
  initModel();
});

defineExpose({
  open: (exts?: any) => {
    model.value = { ...exts };
    show.value = true;
  }
});
</script>

<template>
  <el-dialog v-model="show" title="新建文档" :before-close="handleClose">
    <el-form :model="model" label-width="100px">
      <el-form-item label="标题" prop="title">
        <el-input v-model="model.title" placeholder="请输入文档标题" />
      </el-form-item>
      <el-form-item label="文档描述" prop="desc">
        <el-input v-model="model.desc" placeholder="请输入文档描述" />
      </el-form-item>

      <el-form-item label="命名空间" prop="namespace">
        <el-input v-model="model.namespace" disabled />
      </el-form-item>

      <el-form-item label="嵌入模型" prop="embedModel">
        <el-input v-model="model.embedModel" placeholder="嵌入模型" />
      </el-form-item>

      <el-form-item label="路径" prop="sourcePath">
        <el-upload
          ref="upload"
          v-model:file-list="selectFiles"
          drag
          action="/api/v1/knowledge/knoDoc/upload"
          :data="model"
          :auto-upload="false"
          :limit="1"
          :headers="{ Authorization: token?.accessToken || '' }"
          :on-exceed="handleExceed"
          :on-change="onFileChange"
          :on-success="onFileUploaded"
        >
          <div class="el-upload__text">将文件拖拽到此处，或点击选择文件</div>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-space>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </el-space>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped></style>
